<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/7/23
 * Time: 0:13
 */
namespace App\Http\Controllers\Home\Home;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends BaseController
{
    public function index()
    {
//        //获取code
//        $redirect_uri = urlencode('https://www.illuminate888.com/home/index');
//        header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.APPID.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect');

//        $uip_=$_SERVER['REMOTE_ADDR'];
        $user = json_decode(session('User'),true);
//        $gid_=1539;//用户编号 来自新增用户时的回传gid栏位，此资料必须于该新增回传后储存于资料库备用
//        //$gid_ = $user['rob_uid'];
//        $url = "https://robinlintec.com.tw/codeapigo/apitoken_get.asp";
//        $dataStr = "act=0&fid=256888&fps=987452";//标准固定参数
//        $dataStr = $dataStr."&gid=". $gid_."&uip=". $uip_;  //传递参数 gid 和用户IP
//
//        $apidata = $this->http_post_data($url, $dataStr);
////        echo '请求url:'.$url.'<br/>';
////        echo '请求data:'.$dataStr.'<br/>';
////        echo 'curl返回:'.$apidata.'<br/>';
//        $api_arr=explode("-",$apidata);
//        //echo $apidata;
//        $paper_show=0;
//        $token_ = '';
//        $data = [];
//        if (count($api_arr)>6){
//            if($api_arr[0]=="robinlintec"){
//
//                if($api_arr[1]=="0"){
//
//                    $token_=$api_arr[2];
//                    $paper_show=1; //表示目前状态是可以读取报表的
//                }
//            }
//        }
//        $data['paper_show'] = $paper_show;
//        $data['gid_'] = $gid_;
//        $data['token_'] = $token_;
        $data['user'] = $user;
        if(empty($user['nickname']) || empty($user['wx_avatar']))
        {
            return redirect("/home/getCode");
        }
        return view('Home.Home.index')->withData($data);
    }

    public function getCode()
    {
        $redirect_uri = urlencode('https://www.illuminate888.com/home/getWxInfo');
        header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.APPID.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect');
    }

    public function getWxInfo()
    {
        if(!empty($_GET['code']))
        {
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".SECRET."&code=".$_GET['code']."&grant_type=authorization_code";
            $getInfo = $this->http_get_data($url);
            $getInfo = json_decode($getInfo,true);
            if(!empty($getInfo['access_token']) && !empty($getInfo['openid']))
            {
                $getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$getInfo['access_token']."&openid=".$getInfo['openid']."&lang=zh_CN";
                $getUserInfo = $this->http_get_data($getUserInfoUrl);
                $getUserInfo = json_decode($getUserInfo,true);
                if(!empty($getUserInfo['nickname']) && !empty($getUserInfo['headimgurl']))
                {
                    $user = json_decode(session('User'),true);
                    if(!empty($user['id']))
                    {
                        DB::table('user')
                            ->where('id',$user['id'])
                            ->update(['open_id'=>$getInfo['openid'],'wx_avatar'=>$getUserInfo['headimgurl'],'nickname'=>base64_encode($getUserInfo['nickname'])]);
                        $user['nickname'] = base64_encode($getUserInfo['nickname']);
                        $user['wx_avatar'] = $getUserInfo['headimgurl'];
                        session(['User' => json_encode($user,true)]);
                        header('Location:/home/index');
                    }else{
                        header('Location:/home/index');
                    }
                }else{
                    header('Location:/home/index');
                }
            }else{
                header('Location:/home/index');
            }
        }else{
            header('Location:/home/index');
        }
    }
    private function http_get_data($url)
    {
        //初始化
         $curl = curl_init();
         //设置抓取的url
         curl_setopt($curl, CURLOPT_URL, $url);
         //设置头文件的信息作为数据流输出
         curl_setopt($curl, CURLOPT_HEADER, 0);
         //设置获取的信息以文件流的形式返回，而不是直接输出。
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         //执行命令
         $data = curl_exec($curl);
         //关闭URL请求
         curl_close($curl);
         //显示获得的数据
         return $data;
    }
    private function http_post_data($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }

    public function mymoney()
    {
        $data = [];
        $data['userInfo'] = json_decode(session('User'),true);
        $data['order'] = DB::table('order')
            ->select('order.pay_time','user.name','user.phone','order.paymoney')
            ->leftJoin('user','order.uid','=','user.id')
            ->where('order.pid',$data['userInfo']['id'])
            ->get();
        return view('Home.Home.mymoney')->withData($data);
    }

    public function getmoney()
    {
        $data = [];
        $data[] = DB::table('system_img')
            ->first();
//        return view('Home.Home.getmoney')->withData($data);
        return view('Home.Home.getmoney1')->withData($data);
    }

    public function gettalk()
    {
        $userInfo = json_decode(session('User'),true);
        //检测当前用户是否已经支付过申请测试
        $hasPay = DB::table('order')
            ->where('uid',$userInfo['id'])
            ->where('status',2)
            ->where('type',1)
            ->first();
        if(empty($hasPay->id))
        {
            return header('Location:'.__BASE__.'/home/checkjc');
            return;
        }

        $uip_=$_SERVER['REMOTE_ADDR'];
        $user = json_decode(session('User'),true);
//        $gid_=1539;//用户编号 来自新增用户时的回传gid栏位，此资料必须于该新增回传后储存于资料库备用
        $gid_ = $user['rob_uid'];
        $url = "https://robinlintec.com.tw/codeapigo/apitoken_get.asp";
        $dataStr = "act=0&fid=256888&fps=987452";//标准固定参数
        $dataStr = $dataStr."&gid=". $gid_."&uip=". $uip_;  //传递参数 gid 和用户IP

        $apidata = $this->http_post_data($url, $dataStr);
//        echo '请求url:'.$url.'<br/>';
//        echo '请求data:'.$dataStr.'<br/>';
//        echo 'curl返回:'.$apidata.'<br/>';
        $api_arr=explode("-",$apidata);
        //echo $apidata;
        $paper_show=0;
        $token_ = '';
        $data = [];
        if (count($api_arr)>6){
            if($api_arr[0]=="robinlintec"){

                if($api_arr[1]=="0"){

                    $token_=$api_arr[2];
                    $paper_show=1; //表示目前状态是可以读取报表的
                }
            }
        }
        $data['paper_show'] = $paper_show;
        $data['gid_'] = $gid_;
        $data['token_'] = $token_;
        return view('Home.Home.gettalk')->withData($data);
    }

    public function checkjc()
    {
        $data = [];
        $userInfo = json_decode(session('User'),true);
        //检测当前用户是否已经支付过申请测试
        $hasPay = DB::table('order')
                        ->where('uid',$userInfo['id'])
                        ->where('status',2)
                        ->where('type',1)
                        ->first();
        if(!empty($hasPay->id))
        {
            return header('Location:'.__BASE__.'/home/checkjcsuccess');
            return;
        }
        require_once base_path()."/vendor/wxpay/lib/WxPay.Api.php";
        require_once base_path()."/vendor/wxpay/example/WxPay.JsApiPay.php";
        require_once base_path()."/vendor/wxpay/example/WxPay.Config.php";
        require_once base_path().'/vendor/wxpay/example/log.php';
        //初始化日志
        $logHandler= new \CLogFileHandler(base_path().'/vendor/wxpay/logs/'.date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

        //①、获取用户openid
        try{

            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();

            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("申请检测支付199");
            $input->SetAttach("申请检测支付199");
            $orderNo = $userInfo['id'].date("YmdHis").rand(10000,99999);
            $input->SetOut_trade_no($orderNo);
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("申请检测支付199");
            $input->SetNotify_url("https://www.illuminate888.com/home/notify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            $jsApiParameters = $tools->GetJsApiParameters($order);
            $data['jsApiParameters'] = $jsApiParameters;
            //订单信息入库
            $insert['order_no'] = $orderNo;
            $insert['uid'] = $userInfo['id'];
            $insert['type'] = 1;
            $insert['paymoney'] = 19900;
            if(!empty($userInfo['pid'])){
                $insert['pid'] = $userInfo['pid'];
            }
            $insert['status'] = 1;
            $insert['create_time'] = time();
            DB::table('order')->insert($insert);
        } catch(Exception $e) {
            \Log::ERROR(json_encode($e));
        }
        return view('Home.Home.checkjc')->withData($data);
    }

    public function checkjcsuccess()
    {
        $data = [];
        $data[] = DB::table('system_img')
                    ->first();
        return view('Home.Home.checkjcsuccess')->withData($data);
    }
    public function checkzx()
    {
        $data = [];
        $userInfo = json_decode(session('User'),true);
        //检测当前用户是否已经支付过申请测试
        $hasPay = DB::table('order')
            ->where('uid',$userInfo['id'])
            ->where('status',2)
            ->where('type',2)
            ->first();
        if(!empty($hasPay->id))
        {
            return header('Location:'.__BASE__.'/home/checkzxsuccess');
            return;
        }
        require_once base_path()."/vendor/wxpay/lib/WxPay.Api.php";
        require_once base_path()."/vendor/wxpay/example/WxPay.JsApiPay.php";
        require_once base_path()."/vendor/wxpay/example/WxPay.Config.php";
        require_once base_path().'/vendor/wxpay/example/log.php';
        //初始化日志
        $logHandler= new \CLogFileHandler(base_path().'/vendor/wxpay/logs/'.date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);

        //①、获取用户openid
        try{

            $tools = new \JsApiPay();
            $openId = $tools->GetOpenid();

            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("申请咨询支付200");
            $input->SetAttach("申请咨询支付200");
            $orderNo = $userInfo['id'].date("YmdHis").rand(10000,99999);
            $input->SetOut_trade_no($orderNo);
            $input->SetTotal_fee("1");
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("申请咨询支付200");
            $input->SetNotify_url("https://www.illuminate888.com/home/notify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            $jsApiParameters = $tools->GetJsApiParameters($order);
            $data['jsApiParameters'] = $jsApiParameters;
            //订单信息入库
            $insert['order_no'] = $orderNo;
            $insert['uid'] = $userInfo['id'];
            $insert['type'] = 2;
            $insert['paymoney'] = 20000;
            if(!empty($userInfo['pid'])){
                $insert['pid'] = $userInfo['pid'];
            }
            $insert['status'] = 1;
            $insert['create_time'] = time();
            DB::table('order')->insert($insert);
        } catch(Exception $e) {
            \Log::ERROR(json_encode($e));
        }
        return view('Home.Home.checkzx')->withData($data);
    }

    public function checkzxsuccess()
    {
        $data = [];
        $data[] = DB::table('system_img')
            ->first();
        return view('Home.Home.checkzxsuccess')->withData($data);
    }

}